import React, { useState, useEffect, useRef } from 'react'
import style from './Login.module.css'
import axios from './axios'
import { useNavigate } from 'react-router-dom'
import { Form, Input, Button, Toast, Tabs } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons';
import md5 from 'md5';

export default function Login() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [visible, setVisible] = useState(false);
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [isSending, setIsSending] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [activeTab, setActiveTab] = useState('account');
  const navigate = useNavigate();
  const timer = useRef(null);
  const [errors, setErrors] = useState({});

  // 清理定时器
  useEffect(() => {
    return () => {
      if (timer.current) {
        clearInterval(timer.current);
      }
    };
  }, []);

  // 发送验证码
  const handleSendCode = async () => {
    if (!phone) {
      Toast.show({ content: '请输入手机号', duration: 1000 });
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Toast.show({ content: '手机号格式不正确', duration: 1000 });
      return;
    }

    try {
      Toast.show({
        icon: 'loading',
        content: '发送中...',
        duration: 0,
      });

      const res = await axios.post(`/jjx/send-sms?phoneNumber=${phone}`);

      Toast.clear();

      if (res.data.success) {
        setIsSending(true);
        setCountdown(60);

        Toast.show({
          content: '验证码已发送',
          duration: 2000
        });

        // 开始倒计时
        timer.current = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer.current);
              setIsSending(false);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        Toast.show({
          content: res.data.message || '发送失败，请重试',
          duration: 2000
        });
      }
    } catch (error) {
      Toast.clear();
      Toast.show({
        content: '发送失败，请重试',
        duration: 2000
      });
      console.error('发送验证码错误:', error);
    }
  };

  // 验证用户名
  const validateUsername = (username) => {
    if (!username) {
      return '请输入用户名';
    }
    if (username.length < 2 || username.length > 20) {
      return '用户名长度应在2-20个字符之间';
    }
    if (!/^[\u4e00-\u9fa5a-zA-Z0-9_]+$/.test(username)) {
      return '用户名只能包含中文、字母、数字和下划线';
    }
    return '';
  };

  // 验证密码
  const validatePassword = (password) => {
    if (!password) {
      return '请输入密码';
    }
    if (password.length < 6 || password.length > 20) {
      return '密码长度应在6-20个字符之间';
    }
    return '';
  };

  // 账号密码登录
  const handleLogin = async () => {
    // 验证所有字段
    const newErrors = {
      username: validateUsername(username),
      password: validatePassword(password),
    };

    setErrors(newErrors);

    // 检查是否有错误
    if (Object.values(newErrors).some(error => error !== '')) {
      Toast.show({
        content: '请检查输入信息',
        duration: 2000,
      });
      return;
    }

    try {
      Toast.show({
        icon: 'loading',
        content: '登录中...',
        duration: 0,
      });

      const res = await axios.post('/jjx/login', {
        username,
        password: md5(password),
      });

      Toast.clear();

      if (res.data.code === 200) {
        // 存储用户信息到sessionStorage
        sessionStorage.setItem('id', res.data.data.userId);
        sessionStorage.setItem('username', res.data.data.username);
        sessionStorage.setItem('avatar', res.data.data.avatar || '');
        sessionStorage.setItem('accessToken', res.data.accessToken);
        sessionStorage.setItem('refreshToken', res.data.refreshToken);

        Toast.show({
          content: '登录成功',
          duration: 1000,
        });
        navigate('/square');
      } else {
        Toast.show({
          content: res.data.msg || '登录失败',
          duration: 2000,
        });
      }
    } catch (err) {
      Toast.clear();
      Toast.show({
        content: '登录失败',
        duration: 2000,
      });
      console.error('登录错误:', err);
    }
  };

  // 手机号登录
  const handlePhoneLogin = async () => {
    // 手机号验证
    if (!phone) {
      Toast.show({ content: '请输入手机号', duration: 1000 });
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Toast.show({ content: '请输入正确的手机号格式', duration: 1000 });
      return;
    }
    // 验证码验证
    if (!code) {
      Toast.show({ content: '请输入验证码', duration: 1000 });
      return;
    }
    if (!/^\d{4,6}$/.test(code)) {
      Toast.show({ content: '验证码格式不正确', duration: 1000 });
      return;
    }

    try {
      Toast.show({
        icon: 'loading',
        content: '登录中...',
        duration: 0,
      });

      const res = await axios.post('/jjx/login/phone', { phone, code });

      Toast.clear();

      if (res.data.code === 200) {
        // 存储用户信息到sessionStorage
        sessionStorage.setItem('id', res.data.data.id);
        sessionStorage.setItem('username', res.data.data.username);
        sessionStorage.setItem('avatar', res.data.data.avatar || '');
        sessionStorage.setItem('accessToken', res.data.accessToken);
        sessionStorage.setItem('refreshToken', res.data.refreshToken);

        Toast.show({
          content: '登录成功',
          duration: 1000,
        });
        navigate('/square');
      } else {
        Toast.show({
          content: res.data.msg || '登录失败',
          duration: 2000,
        });
      }
    } catch (err) {
      Toast.clear();
      Toast.show({
        content: '登录失败',
        duration: 2000,
      });
      console.error('登录错误:', err);
    }
  };

  return (
    <div className={style['login-page']}>
      <div className={style['form-wrapper']}>
        <h2 className={style.title}>登录</h2>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.Tab title='账号密码登录' key='account'>
            <Form layout='vertical' className={style.form}>
              <Form.Item label='用户名'>
                <Input
                  placeholder='请输入用户名'
                  clearable
                  value={username}
                  onChange={val => {
                    setUsername(val);
                    setErrors(prev => ({
                      ...prev,
                      username: validateUsername(val)
                    }));
                  }}
                  className={errors.username ? style.inputError : ''}
                />
                <div className={style.formTip}>
                  {errors.username || '2-20个字符，可包含中文、字母、数字和下划线'}
                </div>
              </Form.Item>

              <Form.Item
                label='密码'
                extra={
                  <div className={style.eye}>
                    {!visible ? (
                      <EyeInvisibleOutline onClick={() => setVisible(true)} />
                    ) : (
                      <EyeOutline onClick={() => setVisible(false)} />
                    )}
                  </div>
                }
              >
                <Input
                  placeholder='请输入密码'
                  clearable
                  type={visible ? 'text' : 'password'}
                  value={password}
                  onChange={val => {
                    setPassword(val);
                    setErrors(prev => ({
                      ...prev,
                      password: validatePassword(val)
                    }));
                  }}
                  className={errors.password ? style.inputError : ''}
                />
                <div className={style.formTip}>
                  {errors.password || '6-20个字符'}
                </div>
              </Form.Item>

              <div className={style['remember-me']}>
                <input type="checkbox" id="remember" />
                <label htmlFor="remember">记住我</label>
                <a href="#" className={style['forgot-password']}>忘记密码？</a>
              </div>

              <button className="adm-button" onClick={handleLogin}>
                登录
              </button>
            </Form>
          </Tabs.Tab>

          <Tabs.Tab title='手机号登录' key='phone'>
            <Form layout='vertical' className={style.form}>
              <Form.Item label='手机号' name='phone'>
                <Input
                  placeholder='请输入手机号'
                  clearable
                  type="tel"
                  value={phone}
                  onChange={val => setPhone(val)}
                />
              </Form.Item>
              <Form.Item
                label='验证码'
                name='code'
                extra={
                  <Button
                    size='small'
                    disabled={isSending}
                    onClick={handleSendCode}
                    className={style['send-code-btn']}
                  >
                    {isSending ? `${countdown}s后重试` : '发送验证码'}
                  </Button>
                }
              >
                <Input
                  placeholder='请输入验证码'
                  clearable
                  value={code}
                  onChange={val => setCode(val)}
                />
              </Form.Item>

              <button className="adm-button" onClick={handlePhoneLogin}>
                登录
              </button>
            </Form>
          </Tabs.Tab>
        </Tabs>

        <div className={style['to-register-tip']}>
          还没有账号？
          <a className={style['tip-link']} onClick={() => navigate('/register')}>
            马上注册
          </a>
          <span className={style['tip-emoji']}>👉</span>
        </div>
      </div>
    </div>
  )
}
